<template>
  <div class="ek-upload-image">
    <el-upload
      v-model:file-list="value"
      class="ek-upload-image-box"
      :action="action"
      :multiple="multiple"
      :disabled="disabled"
      :accept="accept"
      :limit="limit"
      :auto-upload="autoUpload"
      :before-upload="handleBeforeUpload"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-remove="handleBeforeRemove"
      :on-exceed="handleExceed"
      :on-success="handleSuccess"
      :on-error="handleError"
      :on-progress="handleProgress"
      :on-change="handleChange"
      list-type="picture-card"
      :headers="headers"
    >
      <el-icon class="icon iconfont icon-increase"></el-icon>
    </el-upload>
    <ekPeviewImage
      :imageList="imageList"
      :visiable="visiable"
      :initialIndex="imageIndex"
      @on-close="handleClose"
      v-if="visiable"
    ></ekPeviewImage>
  </div>
</template>

<script setup>
import { formatFileSize } from "@/utils/common";
import {
  defineProps,
  defineEmits,
  computed,
  ref,
  getCurrentInstance,
  watch,
} from "vue";
import ekPeviewImage from "@/components/business/ekPeviewImage/index.vue";
import { getToken } from '@/utils/sys';
const props = defineProps({
  // 值
  modelValue: {
    type: String,
    default: '',
  },
  // 禁用
  disabled: {
    type: Boolean,
    default: false,
  },
  // 上传地址
  action: {
    type: String,
    default: "/business/upload/upload",
  },
  // 多文件上传
  multiple: {
    type: Boolean,
    default: false,
  },
  // 上传文件类型
  accept: {
    type: String,
    default: "image/png,image/jpg,image/jpeg,image/gif,image/bmp",
  },
  // 上传文件数量限制
  limit: {
    type: Number,
    default: 0,
  },
  // 上传文件大小限制,0不限制
  size: {
    type: Number,
    default: 0,
  },
  // 自动上传
  autoUpload: {
    type: Boolean,
    default: true,
  },
  // 请求头
  headers: {
    type: Object,
    default: {
      Authorization: getToken()
    },
  }
});
const {
  appContext: {
    config: { globalProperties },
  },
} = getCurrentInstance();

const { $storage, $ekMessage } = globalProperties;

const emit = defineEmits([
  "update:modelValue",
  "on-preview",
  "on-success",
  "on-error",
]);

let fileList = ref([]);
let value = props.modelValue ? JSON.parse(props.modelValue): [];
fileList.value = props.modelValue ?  JSON.parse(props.modelValue) : [];

watch(
  () => props.modelValue,
  (newVal) => {
    value = newVal ? JSON.parse(newVal): [];
    fileList.value = newVal ?  JSON.parse(newVal) : [];
  }
);
// 预览列表
const imageList = computed({
  get() {
    return fileList.value?.length
      ? fileList.value.map((item) => {
          return item.url;
        })
      : [];
  },
});
// 默认显示图片预览下标
let imageIndex = ref(0);

function getFileList(files) {
  let list = [];
  files.forEach((item) => {
    delete item.uid;
    delete item.status;
    if (item.raw) {
      list.push(item.response.data);
    } else {
      list.push(item);
    }
  });
  return list;
}
// 上传之前
function handleBeforeUpload(rawFile) {
  // 进行文件类型校验
  if (props.accept != "*") {
    let accept = props.accept.split(",");
    console.log(rawFile,'rawFilerawFile')
    let fileType = rawFile.type;
    if (!accept.includes(fileType)) {
      $ekMessage.error(`文件类型不正确，请上传${props.accept}类型的文件`);
      return false;
    }
  }
  // 进行文件大小校验
  if (props.size != 0) {
    if (rawFile.size > props.size) {
      $ekMessage.error(`文件大小不能超过${formatFileSize(props.size)}`);
      return false;
    }
  }
}

// 是否显示
const visiable = ref(false);

function handleClose() {
  visiable.value = false;
}
// 点击文件列表中已经上传的文件
function handlePreview(uploadFile) {
  imageIndex.value = fileList.value.findIndex(item => item.path === uploadFile.path);
  visiable.value = true;
  emit("on-preview", uploadFile);
}
function handleBeforeRemove(uploadFile, uploadFiles) {}
// 移除文件列表中已经上传的文件
function handleRemove(uploadFile, uploadFiles) {
  let newfileList = [];
  if (uploadFiles.length) {
    newfileList = getFileList(JSON.parse(JSON.stringify(uploadFiles)));
    fileList.value = JSON.parse(JSON.stringify(newfileList));
  } else {
    fileList.value = [];
  }
  emit("update:modelValue", JSON.stringify(newfileList));
}
// 超出上传数限制
function handleExceed(files, uploadFiles) {
  $ekMessage.warning("超出文件上传数限制");
}
// 文件上传成功时的钩
function handleSuccess(response, uploadFile, uploadFiles) {
  console.log(response, 'uploadFileuploadFile')
  emit("on-success", response, uploadFile, uploadFiles);
  let newfileList = getFileList(JSON.parse(JSON.stringify(uploadFiles)));
  fileList.value = JSON.parse(JSON.stringify(newfileList));
  emit("update:modelValue", JSON.stringify(newfileList));
}
// 文件上传失败时的钩子
function handleError(error, uploadFile, uploadFiles) {
  // emit("on-error", error, uploadFile, uploadFiles);
  $ekMessage.error(error.message);
}
// 文件上传时的钩子
function handleProgress(event, uploadFile, uploadFiles) {
  // emit("on-progress", event, uploadFile, uploadFiles);
}
// 文件上传的钩子
function handleChange(uploadFile, uploadFiles) {}
</script>

<style scoped lang="scss">
.ek-upload-image {
  // width: 220px;
  .ek-upload-image-box {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    .ek-upload-image-btn {
    }
    :deep(.el-upload-list) {
      // width: 220px;
    }
  }
}
</style>
